<template>
  <div class="image_wrap">
    <el-form ref="formData" :model="formData" :rules="rules" label-width="180px">
      <el-form-item label="商品主图片（未精修）" prop="mainImage">
        <Upload
          :readOnly="readOnly"
          :maxLen="1"
          :defaultList="echoImages.mainImage"
          :format="['jpg', 'jpeg', 'png']"
          @handleChangeImage="files => { setImageListByType('mainImage', files) }"
        />
      </el-form-item>
      <el-form-item label="商品主图片（精修）" prop="mainImageTrimming">
        <Upload
          :readOnly="readOnly"
          :maxLen="1"
          :defaultList="echoImages.mainImageTrimming"
          :format="['jpg', 'jpeg', 'png']"
          @handleChangeImage="files => { setImageListByType('mainImageTrimming', files) }"
        />
      </el-form-item>
      <el-form-item label="商品多角度图（未精修）" prop="multiImage">
        <Upload
          :readOnly="readOnly"
          :showTip="true"
          :isMultiple="true"
          :defaultList="echoImages.multiImage"
          :maxLen="5"
          :format="['jpg', 'jpeg', 'png']"
          @handleChangeImage="files => { setImageListByType('multiImage', files) }"
        />
      </el-form-item>
      <el-form-item label="商品多角度图（精修）" prop="multiImageTrimming">
        <Upload
          :readOnly="readOnly"
          :showTip="true"
          :isMultiple="true"
          :defaultList="echoImages.multiImageTrimming"
          :maxLen="5"
          :format="['jpg', 'jpeg', 'png']"
          @handleChangeImage="files => { setImageListByType('multiImageTrimming', files) }"
        />
      </el-form-item>
      <el-card shadow="never">
        <div slot="header">
          <span v-if="isRequired" class="error_color">*</span>
          <span>详情信息</span>
        </div>
        <IQuill
          v-model="formData.imageDescribe"
          :readOnly="readOnly"
          :toolbar="readOnly ? false : undefined"
        />
      </el-card>
    </el-form>
  </div>
</template>
<script>
import Upload from '@/components/common/upload'; // 上传组件
import IQuill from '@/components/quill'; // 编辑器组件
import { TRIM_TYPES_ENUMS } from './constants';
export default {
  components: {
    Upload,
    IQuill
  },
  props: {
    dataSource: {
      type: Object,
      default: () => ({})
    },
    rules: { // 必填规则
      type: Object,
      default: () => ({})
    },
    readOnly: { // 是否只读
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      formData: {
        mainImage: [], // 商品主图片（未精修）
        mainImageTrimming: [], // 商品主图片（精修）
        multiImage: [], // 商品多角度图（未精修）
        multiImageTrimming: [], // 商品多角度图（精修）
        imageDescribe: '', // 详情信息
        imageDescribeUuid: '' // 详情信息uuid，后端生成，有值就传
      },
      // 回显图片实例，套用formData会出现组件数据错乱问题
      echoImages: {
        mainImage: [], // 商品主图片（未精修）
        mainImageTrimming: [], // 商品主图片（精修）
        multiImage: [], // 商品多角度图（未精修）
        multiImageTrimming: [], // 商品多角度图（精修）
      }
    }
  },
  watch: {
    dataSource: {
      handler (data) {
        this.initFormData(data)
        this.initEchoImages()
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    // 图文是否必填
    isRequired () {
      const requireFlag = this.rules && Object.keys(this.rules).length > 0
      return requireFlag
    },
    // 图片为空（精修或非精修图至少上传1张）
    hasNoImages () {
      const checkNames = ['mainImage', 'mainImageTrimming', 'multiImage', 'multiImageTrimming']
      const isEmpty = checkNames.every(item => this.formData[item].length === 0)
      return isEmpty
    },
    // 图文为空
    isNullImageText () {
      const isNull = this.hasNoImages && this.isNullImageDescribe
      return isNull
    },
    // 图文已完善
    isCompleteImageText () {
      const checkNames = ['mainImageTrimming', 'multiImageTrimming']
      const hasVal = checkNames.every(item => this.formData[item].length !== 0)
      return hasVal && !this.isNullImageDescribe
    },
    // 富文本为空
    isNullImageDescribe () {
      const isNull = !this.formData.imageDescribe || this.formData.imageDescribe == '<p><br></p>'
      return isNull
    }
  },
  methods: {
    initFormData (data) {
      const { mainImage, mainImageTrimming, multiImage } = data
      const multiImageList = this.getMultiImageList(multiImage, TRIM_TYPES_ENUMS.Notrimming, true)
      const multiImageTrimming = this.getMultiImageList(multiImage, TRIM_TYPES_ENUMS.Trimming, true)
      this.formData = {
        mainImage: mainImage ?? [],
        mainImageTrimming: mainImageTrimming ?? [],
        multiImage: multiImageList,
        multiImageTrimming: multiImageTrimming,
        imageDescribe: data?.imageDescribe ?? '',
        imageDescribeUuid: data?.imageDescribeUuid ?? ''
      }
    },
    initEchoImages () {
      const { mainImage, mainImageTrimming, multiImage, multiImageTrimming } = this.formData
      this.setEchoImageList('mainImage', mainImage)
      this.setEchoImageList('mainImageTrimming', mainImageTrimming)
      this.setEchoImageList('multiImage', multiImage)
      this.setEchoImageList('multiImageTrimming', multiImageTrimming)
    },
    // 根据类型设置图片集合
    setImageListByType (typeName, files) {
      this.formData[typeName] = files
      this.echoImages[typeName] = files
    },
    // 设置回显图片数据集合
    setEchoImageList (typeName, files) {
      if (!files) return
      this.echoImages[typeName] = typeof files === 'string'
        ? [{ url: files }]
        : files.map(item => ({ url: item }))
    },
    // 获取图片提交入参
    getImagesParams () {
      const multiImageList = this.getMultiImageList(this.formData.multiImage, TRIM_TYPES_ENUMS.Notrimming)
      const multiImageTrimmingList = this.getMultiImageList(this.formData.multiImageTrimming, TRIM_TYPES_ENUMS.Trimming)
      const multiImage = [...multiImageList, ...multiImageTrimmingList]
        .map(item => ({ ...item, imageKey: item?.imageKey?.url ?? item?.imageKey ?? '' }))
        .filter(item => item)
      return {
        mainImage: this.formData.mainImage[0]?.url,
        mainImageTrimming: this.formData.mainImageTrimming[0]?.url,
        multiImage,
        imageDescribe: this.formData.imageDescribe,
        imageDescribeUuid: this.formData.imageDescribeUuid
      }
    },
    // 获取多角度图片集合
    getMultiImageList (list, trimmingType, requireFilter) {
      if (!list || list.length === 0) return []
      if (requireFilter) {
        const filterList = list
          .filter(item => item.trimming == trimmingType)
          .map(item => item.imageKey)
        return filterList
      }
      const multiImages = list.map((item, index) => ({
        trimming: trimmingType,
        position: index,
        imageKey: item
      }))
      return multiImages
    },
    // 设置回显值给表单数据
    setEchoToFormData () {
      for (const key in this.echoImages) {
        if (this.echoImages[key] && this.echoImages[key].length !== 0) {
          this.formData[key] = this.echoImages[key]
        }
      }
    },
    // 必填校验
    validateImgTextInfo (callback) {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.isNullImageDescribe) return this.$message.warning('详情信息不能为空')
          callback()
        } else {
          this.$message.warning('必填项不能为空')
        }
      });
    },
    // 清空所有图文状态
    clearAllState () {
      const imgKeys = ['mainImage', 'mainImageTrimming', 'multiImage', 'multiImageTrimming']
      imgKeys.forEach(key => {
        this.formData[key] = []
        this.echoImages[key] = []
      })
      this.formData.imageDescribe = ''
      this.formData.imageDescribeUuid = ''
    },
    // 获取提交图文信息
    getImageInfo () {
      this.setEchoToFormData()
      return this.getImagesParams()
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/ .i-quill {
    height: 100%;
  }
</style>
